var mqtt = require('mqtt')

var clientId = 'dev'//设备名称
    username = ''//产品ID
    password = '' //token
    topic = `$sys/${username}/${clientId}/dp/post/json`//用于订阅和发布的主题

    online = 0//用于退出连接，不是必须
//返回一个消息对象
function getdata()
{
    return {
	id:555,
	dp: {
	    heart: [{
		v: 66,
		t: new Date().getTime()
	    }],
	    oblood: [{
		v: "50%",
		t: new Date().getTime()
	    }]

	}
    }
}
//连接，并返回客户端对象，此处的地址为非ssl加密的地址
var client = mqtt.connect('mqtt://183.230.40.96:1883',{
	clientId,
	username,
	password
})

client.on('connect',()=>{
	console.log("200 ok");
    //订阅主题，只需要修改topic，后面的'/+'不动
	client.subscribe(topic+'/+',(err)=>{
		if (!err)
			console.log("subscribe success!");
		else
			console.log("err");
	})
})


client.on("message",(topic,message)=>{
    //监听message事件，有相关主题消息发布时触发
	console.log(message.toString())
})

var task = setInterval(()=>{
        online++;
        var obj = getdata();
        client.publish(topic,JSON.stringify(obj))
        if(online > 50)
        {
            client.end();
            console.log("已断开连接");
        }
},3000)
